package JackSu.project_model;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Syzer
 * @Description: 观察者模式
 * @DateTime: 2021/7/16 15:07
 */
public class ObserverTest {

    private abstract static class Publish {
        List<Subscriber> subscriberList = new ArrayList<>(2);

        public void add(Subscriber subscriber) {
            subscriberList.add(subscriber);
        }

        public void remove(Subscriber subscriber) {
            subscriberList.remove(subscriber);
        }

        protected abstract void notifySubscriber();
    }

    private static class PublishImpl extends Publish {
        @Override
        protected void notifySubscriber() {
            System.out.println("发布订阅，通知所有订阅者");
            for(Subscriber subscriber : subscriberList) {
                subscriber.response();
            }
        }
    }

    private abstract static class Subscriber {
        abstract void response();
    }

    private static class SubscriberFirst extends Subscriber {
        @Override
        void response() {
            System.out.println("1号订阅号收到通知");
        }
    }

    private static class SubscriberSecond extends Subscriber {
        @Override
        void response() {
            System.out.println("2号订阅号收到通知");
        }
    }

    public static void main(String[] args) {
        Publish publish = new PublishImpl();
        publish.add(new SubscriberFirst());
        publish.add(new SubscriberSecond());
        publish.notifySubscriber();
    }
}
